package com.ilxqx.framework.system.controller.hook.inner;

import com.ilxqx.framework.system.controller.hook.PostDelete;
import com.ilxqx.framework.system.entity.anno.FileKey;
import com.ilxqx.framework.system.upload.qiniu.service.QiNiuImgUploadService;
import com.ilxqx.framework.system.util.ReflectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 删除文件
 * @author venus
 */
@Component
@Slf4j
@Order(0)
public class NotUsedFileDeletion implements PostDelete {

	private final QiNiuImgUploadService qiNiuImgUploadService;

	@Autowired
	public NotUsedFileDeletion(QiNiuImgUploadService qiNiuImgUploadService) {
		this.qiNiuImgUploadService = qiNiuImgUploadService;
	}

	/**
	 * 预处理
	 *
	 * @param entity 实体对象
	 */
	@Override
	public void handle(Object entity) {
		List<Field> fileKeyFields = ReflectionUtils.getAnnotatedFields(entity.getClass(), FileKey.class);
		fileKeyFields.forEach(field -> {
			if (!CharSequence.class.isAssignableFrom(field.getType())) {
				return;
			}
			Object value = ReflectionUtils.getFieldValue(field, entity);
			if (value != null) {
				this.qiNiuImgUploadService.delete(value.toString());
			}
		});
	}

}
